package com.bmd.backgroundmanger.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class FileUploadUtil {

    /**
     * 上传文件
     * @param file 文件
     * @param uploadPath 上传路径
     * @return 文件访问路径
     */
    public static String uploadFile(MultipartFile file, String uploadPath) throws IOException {
        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        // 获取文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 生成新文件名
        String fileName = UUID.randomUUID().toString() + suffix;
        
        // 创建目录
        File dir = new File(uploadPath);
        if (!dir.exists()) {
            boolean created = dir.mkdirs();
            if (!created) {
                throw new IOException("无法创建目录: " + uploadPath);
            }
        }
        
        // 创建文件
        File destFile = new File(uploadPath + File.separator + fileName);
        // 保存文件
        file.transferTo(destFile);
        
        return fileName;
    }
} 